<template>
  <div class="app-container">
    <div class="page-form">
      <el-select
        v-model="queryParams.schoolId"
        placeholder="学校"
        clearable
        filterable
        @change="handleSearch"
        v-hasRole="['admin']"
      >
        <el-option
          v-for="dict in deptList"
          :key="dict.deptId"
          :label="dict.deptName"
          :value="dict.deptId"
        />
      </el-select>
      <el-select
        v-model="queryParams.stageId"
        placeholder="学段"
        clearable
        @change="handleSearch"
      >
        <el-option
          v-for="dict in dict.type.school_segment_type"
          :key="dict.value"
          :label="dict.label"
          :value="dict.value"
        />
      </el-select>
      <el-input
        v-model="queryParams.className"
        placeholder="班级名"
        clearable
        @input="handleSearch"
      />
    </div>
    <el-table
      stripe
      border
      ref="tableList"
      v-loading="loading"
      :data="tableData"
      style="width: 100%"
      @selection-change="handleSelectionChange"
      row-key="id"
    >
      <el-table-column
        type="selection"
        width="55"
        align="center"
        :reserve-selection="true"
      />
      <el-table-column
        label="ID"
        align="center"
        prop="id"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="所属学校"
        align="center"
        prop="schoolName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="班级名称"
        align="center"
        prop="className"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="所属学段"
        align="center"
        prop="tokenId"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.school_segment_type"
            :value="scope.row.stageId"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="所属年级"
        align="center"
        prop="gradeName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="班主任姓名&账号"
        align="center"
        prop="ownTeacherName"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="学生人数"
        align="center"
        prop="studentNum"
        :show-overflow-tooltip="true"
      />

      <el-table-column
        label="操作"
        align="center"
        width="240px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-link
            v-hasPermi="['basic:student:list']"
            type="primary"
            @click="
              $router.push({
                path: '/xsgl',
                query: {
                  deptId: scope.row.deptId,
                  gradeId: scope.row.gradeId,
                  classId: scope.row.id,
                },
              })
            "
            >查看学生</el-link
          >
          <el-link
            v-hasPermi="['system:user:list']"
            type="primary"
            @click="
              $router.push({
                path: '/jsgl',
                query: {
                  deptId: scope.row.deptId,
                  gradeName: scope.row.gradeId,
                  classNames: scope.row.className,
                },
              })
            "
            >关联教师</el-link
          >
          <el-link type="primary" @click="edit(scope.row)">编辑</el-link>
          <el-link type="danger" @click="del(scope.row.id)">删除</el-link>
        </template>
      </el-table-column>
    </el-table>

    <div class="page-bottom">
      <div class="sel-box">
        <p>
          已选 <span>{{ ids.length }}</span> 项 / 共 {{ total }} 项
        </p>
        <el-button type="primary" @click="edit(false)">新增班级</el-button>
        <el-button type="danger" :disabled="multiple" @click="del(false)"
          >批量删除</el-button
        >
      </div>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>

    <el-dialog
      ref="editDialog"
      class="editKmVisible"
      title="创建/编辑新班级"
      :visible.sync="editKmVisible"
      width="436px"
      :before-close="beforeClose"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="学校" prop="schoolId" v-hasRole="['admin']">
          <el-select v-model="editForm.schoolId">
            <el-option
              v-for="dict in deptList"
              :key="dict.deptId"
              :label="dict.deptName"
              :value="dict.deptId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="学段" prop="stageId">
          <el-select v-model="editForm.stageId" @change="stageChange()">
            <el-option
              v-for="dict in dict.type.school_segment_type"
              :key="dict.value"
              :label="dict.label"
              :value="Number(dict.value)"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="年级" prop="gradeId">
          <el-select v-model="editForm.gradeId">
            <el-option
              v-for="dict in dict.type['grade' + editForm.stageId]"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="班级名称" prop="className">
          <el-input v-model="editForm.className" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="班级类型" prop="classType">
          <el-select v-model="editForm.classType">
            <el-option label="普通班级" value="0" />
            <el-option label="重点班级" value="1" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="handleClose">返 回</el-button>
        <el-button type="primary" @click="editSubmit" :loading="loading"
          >保 存</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept } from "@/api/system/dept";
import { classlist, classAdd, classEdit, classDel } from "@/api/jcgl/bjgl";
import { debounce } from "lodash";
export default {
  name: "Basic_bjgl",
  dicts: ["school_segment_type", "grade", "grade1", "grade2", "grade3"],
  data() {
    return {
      firstLoad: true,
      loading: false,

      ids: [],

      total: 0,
      tableData: [],

      multiple: true,

      queryParams: {
        pageNum: 1,
        pageSize: 15,
        schoolId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
        stageId: "",
        className: "",
      },
      editKmVisible: false,
      editForm: {
        schoolId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
        stageId: "",
        gradeId: "",
        className: "",
        classType: "",
      },
      rules: {
        schoolId: [
          { required: true, message: "学校不能为空", trigger: "change" },
        ],
        stageId: [
          { required: true, message: "学段不能为空", trigger: "change" },
        ],
        gradeId: [
          { required: true, message: "年级不能为空", trigger: "change" },
        ],
        className: [
          { required: true, message: "班级名称不能为空", trigger: "blur" },
        ],

        classType: [
          { required: true, message: "班级类型不能为空", trigger: "change" },
        ],
      },
      deptList: [],
    };
  },
  created() {
    this.getList();
    if (this.$auth.hasRole("admin")) {
      listDept().then((res) => {
        this.deptList = res.data.filter((item) => {
          return item.type == 1;
        });
      });
    }
  },
  activated() {
    if (!this.firstLoad) {
      this.getList();
    }
    this.firstLoad = false;
  },
  methods: {
    getList() {
      this.loading = true;
      this.tableData = [];
      classlist(this.queryParams)
        .then((response) => {
          this.tableData = response.rows;
          this.total = response.total;
        })
        .finally(() => {
          this.loading = false;
        });
    },
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    debouncedSearch: debounce(function () {
      this.queryParams.pageNum = 1;
      this.getList();
    }, 500),

    edit(row) {
      if (row) {
        this.editForm.id = row.id;
        this.editForm.schoolId = row.schoolId;
        this.editForm.gradeId = row.gradeId.toString();
        this.editForm.className = row.className;
        this.editForm.classType = row.classType;
        this.editForm.stageId = row.stageId;
      }

      this.editKmVisible = true;
    },

    beforeClose(done) {
      this.editForm = {
        schoolId: this.$auth.hasRole("admin")
          ? ""
          : this.$store.state.user.deptId,
        stageId: "",
        gradeId: "",
        className: "",
        classType: "",
      };
      this.bjlb = [];
      this.$nextTick(() => {
        this.$refs.editForm.clearValidate();
        done();
      });
    },
    handleClose() {
      this.beforeClose(() => {
        this.editKmVisible = false;
      });
    },

    editSubmit() {
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.loading = true;
          let req;
          if (this.editForm.id) {
            req = classEdit;
          } else {
            req = classAdd;
          }
          let data = {
            ...this.editForm,
          };

          if (this.$auth.hasRole("admin")) {
            data.schoolName = this.deptList.filter((item) => {
              return item.deptId == data.schoolId;
            })[0].deptName;
          } else {
            data.schoolName = this.$store.state.user.deptName;
          }

          data.stage = this.selectDictLabel(
            this.dict.type.school_segment_type,
            data.stageId
          );
          data.gradeName = this.selectDictLabel(
            this.dict.type.grade,
            data.gradeId
          );

          req(data)
            .then((res) => {
              this.$modal.msgSuccess("操作成功");
              this.handleClose();
              this.getList();
            })
            .finally(() => {
              this.loading = false;
            });
        }
      });
    },

    del(id) {
      this.$modal.confirm("请确认进行删除操作").then(() => {
        classDel({ ids: id ? [id] : this.ids }).then((res) => {
          this.$modal.msgSuccess("操作成功");
          this.$refs.tableList.clearSelection();
          this.ids = [];
          this.getList();
        });
      });
    },

    handleSearch() {
      this.debouncedSearch();
    },

    stageChange() {
      this.editForm.gradeId = "";
    },
  },
};
</script>

<style lang="scss" scoped>
.editKmVisible {
  .el-input,
  .el-select {
    width: 240px;
  }
}
</style>